package services

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/models"
	"cloud-navigation/global"
	"cloud-navigation/utils"
	"errors"
	"strconv"
)

type adminService struct{}

var AdminService = new(adminService)

// 获取管理员信息
func (adminService *adminService) GetAdminInfo(id string) (admin *models.AdminSafe, err error) {
	intId, _ := strconv.Atoi(id)
	err = global.App.DB.Table("admins").First(&admin, intId).Error
	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}

// 用户注册
func (adminService *adminService) Register(params request.Register) (admin models.Admin, err error) {
	var result = global.App.DB.Where("mobile = ?", params.Mobile).Select("id").First(&models.User{})
	if result.RowsAffected != 0 {
		err = errors.New("手机号已存在")
		return
	}
	admin = models.Admin{Name: params.Name, Mobile: params.Mobile, Password: utils.BcryptMake([]byte(params.Password))}
	err = global.App.DB.Create(&admin).Error
	return
}

// 用户登录
func (adminService *adminService) Login(params request.Login) (admin models.Admin, err error) {
	err = global.App.DB.Where("mobile = ?", params.Mobile).First(&admin).Error
	if err != nil || !utils.BcryptMakeCheck([]byte(params.Password), admin.Password) {
		err = errors.New("用户名不存在或密码错误")
	}
	return
}
